package simorg.actions;

import java.util.ArrayList;
import java.util.Collection;

import simorg.controller.AssignmentController;
import simorg.domain.Assignment;
import simorg.domain.Compound;
import simorg.domain.persistence.AssignmentTable;
import simorg.domain.persistence.CompoundAssignmentJoinTable;
import simorg.domain.persistence.CompoundTable;
import simorg.view.ModelView;
import simorg.view.WebSessionContext;

public class AssignmentSave extends Action {

	public static final String actionName = "save";
	
	public AssignmentSave() {
		super(actionName);
		this.controllerName = AssignmentController.controllerName;
		
	}
	
	@Override
	public ModelView checkAccess(WebSessionContext wc) throws Exception {
		return this.checkAdminAccess(wc);
	}
	
	@Override
	public ModelView process(WebSessionContext wc) throws Exception {
		
		
		Assignment assignmentToSave = AssignmentTable.findById(wc.getDbConnection(), Integer.parseInt(this.getRequestArgs().get(0)));
		
		// Security
		
		// Process post params
		if ( wc.hasReqeustParameter("title")) {
			assignmentToSave.setTitle(wc.getRequestParameter("title"));
		}
		if ( wc.hasReqeustParameter("dueDate")) {
			System.out.println(wc.getRequestParameter("dueDate"));
			assignmentToSave.setDueDate(Assignment.dateFormatter.parse(wc.getRequestParameter("dueDate")));
		}
		if ( wc.hasReqeustParameter("assignedDate")) {
			assignmentToSave.setAssignedDate(Assignment.dateFormatter.parse(wc.getRequestParameter("assignedDate")));
		}
		if ( wc.hasReqeustParameter("numCompoundsToComplete")) {
			assignmentToSave.setNumCompoundsToComplete(Integer.valueOf(wc.getRequestParameter("numCompoundsToComplete")));
		}
	
		AssignmentTable.save(wc.getDbConnection(), assignmentToSave);
		
		// get all the compounds...
		Collection<Compound> allCompounds = CompoundTable.findAll(wc.getDbConnection());
		ArrayList<Integer> chosenIds = new ArrayList<Integer>();
		for ( Compound c : allCompounds ) {
			String param = "compound_" + String.valueOf(c.getId());
			if ( wc.hasReqeustParameter(param)) {
				System.out.println("Compound " + c.getId() + " chosen" );
				chosenIds.add(c.getId());
			}
		}
		CompoundAssignmentJoinTable.setCompoundsForAssignment(wc.getDbConnection(), assignmentToSave.getId(), chosenIds);
		
		
		Action redirect = new CourseView(String.valueOf(assignmentToSave.getCourseId()));
		wc.redirectAdmin(redirect);
		return null;
	}

}
